package com.polaris.live.ui.live.widget.adapter

import androidx.lifecycle.LifecycleCoroutineScope
import com.blankj.utilcode.util.ColorUtils
import com.polaris.live.R
import com.polaris.live.adapter.live.LiveMessageAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.loadIfPresent
import com.polaris.live.databinding.LiveMessageNewFollowerBinding
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.ext.MessageUserExtBean
import com.polaris.live.ui.message.widget.single_message.AbstractLiveMessageItemHolder
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.viewscope.autoDisposeScope
import com.polaris.live.widget.avatar.FrameImageUtils
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * LiveMessageNewFollowerItem
 *
 * @author Created by 半仙 on 2023/12/4/004 19:34
 */
class LiveMessageNewFollowerItem(
    adapter: LiveMessageAdapter,
    binding: LiveMessageNewFollowerBinding,
    private val lifecycleScope: LifecycleCoroutineScope?
) : AbstractLiveMessageItemHolder<LiveMessageNewFollowerBinding>(adapter, binding) {

    override fun bind(item: SendLiveMessage) {
        val ext = item.ext as? MessageUserExtBean?

        mBinding.avatarImg.setImageUrl(ext?.user?.avatar, ext?.user?.userId)
        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(ext?.user?.avatarFrame))

        CommonUtils.setNumberMedal(lifecycleScope, ext?.user?.numberMedal, mBinding.pagImageMe, mBinding.ivImageMe)

        loadIfPresent({ item.span1 }, {
            mBinding.root.autoDisposeScope.launch {
                try {
                    val span = CommonUtils.setSpanData(mBinding.tvContent, item, mAdapter.context)
                    withContext(CoroutineScopeManager.mainDispatcher) {
                        val detailColor =
                            if (ext?.user?.userId == UserManager.getUser().userId) {
                                ColorUtils.getColor(R.color.d2ff4b)
                            } else {
                                ColorUtils.getColor(R.color.white)
                            }
                        span.append(" ${item.content}")
                            .setForegroundColor(detailColor)

                        emit(span.create())
                    }
                } catch (_: Exception) {
                }
            }
        }, {
            mBinding.tvContent.text = it
            item.span1 = it
        })
    }
}